<template>
  <basic-dialog
    :visible.sync="visible"
    :title="'关联商品'"
    :width="'80%'"
    :handleClose="handleCloseDialog"
    :handleOk="handleSubmit"
    :loadingBtn="submitLoading"
    okText="提交"
  >
    <el-card shadow="never" class="demand-card">
      <skus-table
        showSelectCol
        :selectionChange="selectionChange"
        :dataSource="tableInfo.list"
        :columns="tableInfo.columns"
        :loading="tableInfo.loading"
        :tableHeight="450"
        @handleCancelSelect="handleRemoveRow"
      >
        <div slot="content_context">
          <el-button
            type="primary"
            size="mini"
            :disabled="!inquiryEntryIds.length"
            @click="handleBatchDelete"
          >批量删除</el-button
          >
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-download"
            :loading="exportLoading"
            :disabled="!tableInfo.list.length"
            @click="exportTemplate"
          >导出</el-button
          >
          <el-upload
            style="display: inline-block; margin-left: 10px"
            accept=".xls, .xlsx"
            action="/srm-api/product/importTemplate"
            :on-success="onUploadsuccess"
            :before-upload="beforeUpload"
            :on-error="onUploadError"
            :show-file-list="false"
          >
            <el-button size="mini" icon="el-icon-upload2" type="primary"
              >导入</el-button
            >
          </el-upload>
        </div>
      </skus-table>
    </el-card>
    <!-- 选择商品弹框 -->
    <SelectGoods
      :visible.sync="goodsVisible"
      :productType="currentRow.productType"
      :inquiryEntryId="currentRow.inquiryEntryId"
      @getGoodsInfo="handleGoodsSelect"
    />
    <!-- 无销售区域商品 -->
    <SaleAreaTip
      :visible.sync="tipVisible"
      :skuList="noSaleAreaSkuList"
    />
  </basic-dialog>
</template>
<script>
import BasicDialog from '@/components/BasicDialog';
import SkusTable from '@/components/skusTable';
import SelectGoods from '../SelectGoods';
import SaleAreaTip from '../SaleAreaTip';
import skusPage from '@/mixins/commodity/skusPage';
import { createExcelByExport } from '@/utils/bizUtils';
import {
  associatedGoodsSubmitService,
  exportDemandService,
} from '@/api/sourcing/public';
import {
  queryInquirySkuService,
  updateInquirySkuCodeService
} from '@/api/sourcing/demandInquery';
import { isResponseSuccess } from '../../utils';
// import { INQUERY_TIMEOUT_REASON_OPTION } from '@/pages/sourcing/constants';

export default {
  name: 'ReleatedGoods',
  mixins: [skusPage],
  components: {
    BasicDialog,
    SkusTable,
    SelectGoods,
    SaleAreaTip,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    inquirySkuList: {
      type: Array,
      required: true,
      default: () => {
        return []
      },
    },
  },
  data () {
    return {
      submitLoading: false,
      goodsVisible: false,
      currentRow: {},
      tipVisible: false,
      noSaleAreaSkuList: [],
    };
  },

  computed: {
    // 需求id
    inquiryUuids () {
      return this.tableInfo.list.map(item => item.inquiryEntryId)
    },
    // 已勾选需求id
    inquiryEntryIds () {
      return this.tableInfo.selection.map(item => item.inquiryEntryId)
    },
  },
  watch: {
    inquirySkuList: {
      handler (val) {
        this.tableInfo.list = val
        this.initSkuTableColumn()
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    initSkuTableColumn () {
      this.tableInfo.columns = [
        {
          key: 'inquiryEntryId',
          title: '需求ID',
        },
        {
          key: 'skuName',
          title: '需求名称',
        },
        {
          key: 'productTypeStr',
          title: '需求商品类型',
        },
        {
          key: 'specification',
          title: '需求规格',
        },
        {
          key: 'brand',
          title: '需求品牌',
        },
        {
          key: 'normalSkuCode',
          title: '商品代码',
        },
        {
          key: 'normalSkuName',
          title: '商品名称',
          width: 160,
          render: (h, { row }) => {
            return <el-input
              size="mini"
              clearable
              value={row.normalSkuName}
              prefix-icon="el-icon-search"
              onFocus={() => { this.showGoodsDialog(row) }}
              placeholder="请选择商品"
              onClear={() => { this.handleClearGoodsInfo(row) }}
            />
          }
        },
        {
          key: 'action',
          title: '操作',
        }
      ]
    },
    // 显示商品弹窗
    showGoodsDialog (row) {
      this.goodsVisible = true;
      this.currentRow = row;
    },
    // 商品选择
    handleGoodsSelect (data) {
      const {
        skuNo,
        productName,
        mainSupplyNo,
        mainSupplyName,
        costPrice,
        enumTempProduct,
        enableStatus,
        skuUuid
      } = data;
      this.currentRow.normalSkuCode = skuNo;
      this.currentRow.normalSkuName = productName;
      this.currentRow.supplierCode = mainSupplyNo;
      this.currentRow.supplierName = mainSupplyName;
      this.currentRow.costPrice = costPrice;
      this.currentRow.enumTempProduct = enumTempProduct;
      this.currentRow.enableStatus = enableStatus;
      this.currentRow.skuId = skuUuid;
      // 商品和需求为一对一关联关系
      this.tableInfo.list.forEach(element => {
        if (element.normalSkuCode == skuNo && element.inquiryEntryId != this.currentRow.inquiryEntryId) {
          this.handleClearGoodsInfo(element)
        }
      });
    },
    // 清空商品信息
    handleClearGoodsInfo (row) {
      row.normalSkuCode = '';
      row.normalSkuName = '';
      row.supplierCode = '';
      row.supplierName = '';
      row.costPrice = '';
      row.enumTempProduct = '';
      row.enableStatus = '';
      row.skuId = '';
    },
    // 关闭弹框
    handleCloseDialog () {
      this.$emit('update:visible', false);
    },
    // 导出信息数据
    async exportTemplate () {
      const res = await exportDemandService(this.inquiryUuids, state => { this.exportLoading = state })
      if (res) {
        createExcelByExport({ res, excelTitle: '需求模板' });
      }
    },
    beforeUpload () {
      this.tableInfo.loading = true;
    },
    // 导入成功
    onUploadsuccess (res) {
      this.tableInfo.loading = false;
      if (isResponseSuccess(res)) {
        this.tableInfo.list = res.data;
        this.initSkuTableColumn()
      } else {
        this.$message.error('导入异常')
      }
    },
    // 导入成功
    onUploadError () {
      this.tableInfo.loading = false;
      this.$message.error('导入异常')
    },
    // 批量删除
    handleBatchDelete () {
      this.tableInfo.list = _.cloneDeep(this.tableInfo.list).filter(item => !this.inquiryEntryIds.includes(item.inquiryEntryId))
    },
    // 删除需求
    handleRemoveRow ({ index }) {
      this.tableInfo.list.splice(index, 1);
    },
    // 格式化提交数据
    formatSubmitData () {
      return this.tableInfo.list.filter(ele => ele.normalSkuCode).map(item => ({
        skuNo: item.normalSkuCode,
        skuId: item.skuId,
        inquiryEntryId: item.inquiryEntryId,
        enumTempProduct: item.enumTempProduct,
        enableStatus: item.enableStatus,
      }))
    },
    // 提交
    handleSubmit () {
      if (!this.tableInfo.list.length) {
        return this.$message.warning('提交数据不能为空')
      }
      const data = this.formatSubmitData()
      if (data.length == 0) {
        return this.$message.warning('需求全未关联商品, 请至少关联一条')
      }
      this.submitAction({ toast: 1, dataList: data })
    },
    async submitAction (data) {
      const entryIds = data.dataList.map(item => item.inquiryEntryId)
      const res = await associatedGoodsSubmitService(data, state => { this.submitLoading = state })
      if (res) {
        this.verifyIsMulticode(res, () => {
          this.$message.success('提交成功')
          this.handleCloseDialog()
          this.$emit('queryDemandList')
        }, { entryIds })
      }
    },
    // 修改询价需求商品为主码商品
    async updateInquirySkuCode (params) {
      const res = await updateInquirySkuCodeService({
        ...params
      })
      if (res) {
        this.$message.success('操作成功')
        this.getInquiryList()
      }
    },
    // 展示无销售区域商品列表
    showNoSaleAreaTip (skuList) {
      this.tipVisible = true;
      this.noSaleAreaSkuList = skuList;
    },
    // 校验是否一物多码
    verifyIsMulticode (res, callback, params) {
      const { data } = res
      if (data) {
        const { msg, checkType, data } = res.data
        if (checkType == 204) {
          this.showNoSaleAreaTip(data)
        } else {
          this.$confirm(msg, '提示', { type: 'warning' }).then(() => {
            if (checkType == 201) { // 一物多码
              this.updateInquirySkuCode(params)
            } else if (checkType == 202) { // 可直接完结和需继续询价商品同时存在
              this.submitAction({ toast: 2, commit: true, dataList: this.formatSubmitData() })
            }
          }).catch(() => {
            this.submitAction({ toast: 2, commit: false, dataList: this.formatSubmitData() })
          });
        }
      } else {
        callback()
      }
    },
    // 获取需求列表
    async getInquiryList () {
      const res = await queryInquirySkuService(this.inquiryUuids, state => { this.goodsBtnLoading = state })
      if (res) {
        res.data.forEach(item => {
          const { skuName, specification, productTypeStr, inquiryEntryId } = item;
          this.tableInfo.list.forEach(ele => {
            if (ele.inquiryEntryId == inquiryEntryId) {
              ele.skuName = skuName
              ele.specification = specification
              ele.productTypeStr = productTypeStr
            }
          })
        })
      }
    },
  }
};
</script>
<style lang="less">
  .demand-card {
    margin-top: 10px;
  }
  .active-error {
    border: 1px dashed red;
    border-radius: 4px;
    input {
      border: none;
    }
  }
</style>
